package com.hpq.chat.service.srategy.msg;

import com.hpq.chat.dao.MessageDAO;
import com.hpq.chat.domain.dto.ChatMsgRecallDTO;
import com.hpq.chat.domain.enums.MessageTypeEnum;
import com.hpq.chat.domain.model.Message;
import com.hpq.chat.domain.model.msg.MessageExtra;
import com.hpq.chat.domain.model.msg.MsgRecall;
import com.hpq.common.event.MessageRecallEvent;
import com.hpq.user.domain.model.User;
import com.hpq.user.service.cache.UserCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class RecallMsgHandler  extends AbstractMsgHandler<Object> {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private MessageDAO messageDao;
    @Autowired
    private UserCache userCache;
    @Override
    MessageTypeEnum getMsgTypeEnum() {
        return MessageTypeEnum.RECALL;
    }

    @Override
    protected void saveMsg(Message message, Object body) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object showMsg(Message msg) {
        MsgRecall recall = msg.getExtra().getRecall();
        User user = userCache.getUserInfo(recall.getRecallUid());
        if(!Objects.equals(msg.getFromUid(),recall.getRecallUid())){
            return String.format("管理员\"%s\"撤回了一条消息",user.getName());
        }
        return String.format("\"%s\"撤回了一条消息",user.getName());
    }

    public void recall(Long recallUid ,Message message){
        MessageExtra extra = message.getExtra();
        MsgRecall recall = extra.getRecall();
        recall.setRecallUid(recallUid);
        extra.setRecall(recall);
        message.setExtra(extra);
        messageDao.updateById(message);
        applicationEventPublisher.publishEvent(new MessageRecallEvent(this, new ChatMsgRecallDTO(message.getId(), message.getRoomId(), recallUid)));

    }
    @Override
    public Object showReplyMsg(Message msg) {
        return "原消息已被撤回";
    }

    @Override
    public String showContactMsg(Message msg) {
        return "撤回了一条消息";
    }
}
